package com.kevinkk.tree;

import java.util.*;

/**
 * 迭代法 层序 遍历二叉树
 */


public class BinaryTreeLevelOrderTraversal {
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            Deque<TreeNode> que = new ArrayDeque<>();
            if (root != null)
                que.addLast(root);

            while (!que.isEmpty()) {
                int size = que.size();
                List<Integer> row = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode temp = que.removeFirst();
                    row.add(temp.val);
                    if (temp.left != null)
                        que.addLast(temp.left);
                    if (temp.right != null)
                        que.addLast(temp.right);
                }
                res.add(row);
            }
            return res;
        }
    }
}
